<?php
declare(strict_types=1);
namespace app\common\business;

use app\common\lib\Str;
use app\common\lib\Time;
use think\Exception;
use app\common\model\mysql\User as UserModel;

class User extends BusiBase
{
    public function __construct()
    {
        $this->model = new UserModel();
    }

    /**
     * 用户登录流程处理
     *
     * @param array $data
     * @return array|false
     * @throws \think\Exception
     */
    public function login(array $data)
    {
        // 获取 redis 记录当前手机号对应验证码
        $redisCode = Cache(config('redis.code.prefix').$data['phone']);
        // 判断当前手机号对应验证码是否存在
        if (empty($redisCode)) throw new Exception('验证码不存在', config('status.code.code_not_found'));
        // 判断当前手机号对应验证码与提交的验证码是否一直
        if ($redisCode != $data['code']) throw new Exception("验证码错误", config('status.code.code_error'));

        // 根据 phone 获取用户信息
        $user = $this->model->getUserByPhone($data['phone']);
        // 当用户不存在时
        if (!$user) {
            $userData = [
                'username' => $data['phone'],
                'phone'    => $data['phone'],
                'type'     => $data['type']
            ];

            $userId = $this->insert($data, $data['phone']);
            $username = $data['phone'];
        } else {
            // 用户表数据更新部分
            $userId = $user->id;
            $username = $user->username;
            $updateData = [
                'type' => $data['type'],
                'operate_user' => $username
            ];

            $this->edit($userId, $updateData);
        }

        // 保存到 redis 数据
        $redisData = [
            'id' => $userId,
            'username' => $username,
            'phone' => $data['phone'],
            'type' => $data['type']
        ];

        // 获取 token
        $token = Str::getLoginToken($data['phone']);

        // 保存 token 到 redis
        $res = cache(config('redis.token.prefix').$token, $redisData, Time::userLoginExpiresTime($data['type']));

        return $res ? ['token' => $token, 'username' => $username] : false;
    }

    /**
     * 返回正常用户数据
     *
     * @param $id
     * @return array
     */
    public function getNormalUserById(int $id)
    {
        $userInfo = $this->getById($id);
        if (!$userInfo || $userInfo['status'] != config('status.mysql.table_normal')) return [];
        return $userInfo;
    }

    /**
     * 根据用户 ID 修改用户信息
     *
     * @param int $id
     * @param array $data
     * @return bool
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function updateUserById(int $id, array $data)
    {
        // 获取当前用户信息
        $userInfo = $this->getById($id);
        if (!$userInfo) throw new Exception('该用户不存在');

        // 查找当前用户名是否存在
        $nameInfo = $this->model->getUserByUsername($data['username']);
        if ($nameInfo && $nameInfo['id'] != $id) throw new Exception('该用户名已存在');

        // 修改用户信息并返回
        $edit = $this->edit($id, $data);
        return $edit;
    }
}